package com.goldcn.user.controller;


import com.goldcn.interceptor.SystemContext;
import com.goldcn.user.dto.*;
import com.goldcn.user.model.*;
import com.goldcn.user.service.CountService;
import com.goldcn.user.service.OrganizationalService;
import com.goldcn.user.service.UserInfoService;
import com.goldcn.user.vo.UserOrganizationalInfoVo;
import com.goldcn.util.JsonUtil;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 1111 on 2016/11/10.
 */
@Api(value = "用户管理")
@RestController
@RequestMapping(value = "/userinfo")
public class UserInfoController {
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    CountService countService;

    @Autowired
    OrganizationalService organizationalService;


    @ApiOperation(value = "修改用户信息")
    @RequestMapping(method = RequestMethod.POST)
    public Object updateUserInfo(@RequestBody UserInfo userInfo) {
        return userInfoService.updateUserInfo(userInfo, false);
    }

    @ApiOperation(value = "根据ID查询用户")
    @RequestMapping(value = "/{userID}", method = RequestMethod.GET)
    public Object selectByUserID(@PathVariable Long userID) {
        UserInfo ui = userInfoService.selectByUserID(userID);
        UserInfoDto dto = (UserInfoDto) JsonUtil.toBean(JsonUtil.toJson(ui), UserInfoDto.class);
        Organizational org = organizationalService.selectByOID(dto.getOrganizationalID());
        dto.setOrganizationalName(org.getOrganizationalName());
        return dto;
    }

    @ApiOperation(value = "根据ID查询用户级别以及部门级别")
    @RequestMapping(value = "/userType/{userID}", method = RequestMethod.GET)
    public Object selectLevelByUserID(@PathVariable Long userID) {
        return userInfoService.selectLevelByUserID(userID);
    }


    @ApiOperation(value = "根据userID查询用户的溯源信息[销售顾问、销售经理、组织名字]")
    @RequestMapping(value = "/traceability/{userID}", method = RequestMethod.GET)
    public Object selectTraceability(@PathVariable Long userID) {
        return userInfoService.selectTraceability(userID);
    }

    @ApiOperation(value = "根据userID查询用户的溯源信息[销售顾问、销售经理、组织名字]")
    @RequestMapping(value = "/traceability/{userID}/{salesManagerID}/{deptID}", method = RequestMethod.GET)
    public Object selectTraceability(@PathVariable Long userID, @PathVariable Long salesManagerID, @PathVariable Long deptID) {
        return userInfoService.selectTraceability(userID, salesManagerID, deptID);
    }

    @ApiOperation(value = "根据userID查询用户详情[包括交易额]/仅销售顾问在会员列表中type传2，其他情况传1")
    @RequestMapping(value = "/info/{userID}/{type}", method = RequestMethod.GET)
    public Object selectUserByUserID(@PathVariable Long userID, @PathVariable int type) throws Exception {
        return userInfoService.selectUserByUserID(userID, type);
    }

    @ApiOperation(value = "修改状态（0启用，1停用，2未审核）")
    @RequestMapping(value = "/isStop", method = RequestMethod.PUT)
    public Object updateIsStop(@RequestBody StateDto stateDto) {
        return userInfoService.updateIsStop(stateDto);
    }

    @ApiOperation(value = "停用启用（0启用，1停用)")
    @RequestMapping(value = "/isStop/{userID}/{isStop}", method = RequestMethod.GET)
    public Object enableOrDisableUser(@PathVariable Long userID, @PathVariable Integer isStop) {
        return userInfoService.enableOrDisableUser(userID, isStop);
    }

    @ApiOperation(value = "根据条件查询用户列表(type(1系统管理员，2销售经理，3销售顾问，4会员))")
    @RequestMapping(value = "/list/{pageNum}/{pageSize}", method = RequestMethod.POST)
    public Object selectUiList(@PathVariable int pageNum, @PathVariable int pageSize, @RequestBody UserSelectDto selectDto) {
        return userInfoService.selectUiList(pageNum, pageSize, selectDto);
    }

    @ApiOperation(value = "纯粹根据传入条件查询用户列表，并只返回userInfo表信息")
    @RequestMapping(value = "/uiList/{pageNum}/{pageSize}", method = RequestMethod.POST)
    public Object selectUiListByConditon(@PathVariable int pageNum, @PathVariable int pageSize, @RequestBody UserSelectDto selectDto) {
        return userInfoService.selectUiListByConditon(pageNum, pageSize, selectDto);
    }

    @ApiOperation(value = "查询总行的管理账号列表")
    @RequestMapping(value = "/adminList/{pageNum}/{pageSize}", method = RequestMethod.POST)
    public Object selectAdminUserList(@PathVariable int pageNum, @PathVariable int pageSize, @RequestBody List<String> account) {
        return userInfoService.selectAdminUserList(pageNum, pageSize, account.get(0));
    }

    @ApiOperation(value = "查询用户的角色")
    @RequestMapping(value = "/role/{userID}", method = RequestMethod.GET)
    public Object selectUserRoleByUserID(@PathVariable Long userID) {
        return userInfoService.selectUserRoleByUserID(userID);
    }

    @ApiOperation(value = "更新用户角色")
    @RequestMapping(value = "/role/{userID}", method = RequestMethod.PUT)
    public Object updateUserRole(@PathVariable Long userID, @RequestBody List<UserRole> urList) {
        return userInfoService.updateUserRole(userID, urList);
    }

    @ApiOperation(value = "用户新增地址")
    @RequestMapping(value = "/address", method = RequestMethod.POST)
    public Object addAddress(@RequestBody UserAddress userAddress) {
        return userInfoService.addAddress(userAddress);
    }

    @ApiOperation(value = "用户修改地址信息")
    @RequestMapping(value = "/address/update", method = RequestMethod.POST)
    public Object updateAddress(@RequestBody UserAddress userAddress) {
        return userInfoService.updateAddress(userAddress);
    }

    @ApiOperation(value = "删除地址信息")
    @RequestMapping(value = "/address/delete/{id}", method = RequestMethod.GET)
    public Object deleteAddress(@PathVariable Long id) {
        return userInfoService.deleteAddress(id);
    }

    @ApiOperation(value = "按id查询地址信息")
    @RequestMapping(value = "/address/{id}", method = RequestMethod.GET)
    public Object selectAddressByID(@PathVariable Long id) {
        return userInfoService.selectAddressByID(id);
    }

    @ApiOperation(value = "按userID查询地址信息列表")
    @RequestMapping(value = "/addressList/{userID}", method = RequestMethod.GET)
    public Object selectAddressByUserID(@PathVariable Long userID) {
        return userInfoService.selectAddressByUserID(userID);
    }

    @ApiOperation(value = "设置默认地址")
    @RequestMapping(value = "/addressDefault/{id}", method = RequestMethod.GET)
    public Object updateAdressDefault(@PathVariable Long id) {
        return userInfoService.updateAdressDefault(id);
    }

    @ApiOperation(value = "判断会员是否总行下属(是则返回空，不是则返回上级销售经理电话)")
    @RequestMapping(value = "/apply/{userID}", method = RequestMethod.GET)
    public Object judgeHCCBByUserID(@PathVariable Long userID) {
        return userInfoService.judgeHCCBByUserID(userID);
    }

    @ApiOperation(value = "会员提交申请成为销售顾问")
    @RequestMapping(value = "/apply", method = RequestMethod.POST)
    public Object addApply(@RequestBody UserApply userApply) {
        return userInfoService.addApply(userApply);
    }

    @ApiOperation(value = "销售顾问审核(0失败，1成功)")
    @RequestMapping(value = "/apply", method = RequestMethod.PUT)
    public Object updateApplyState(@RequestBody UserApply userApply) {
        return userInfoService.updateApplyState(userApply);
    }

    @ApiOperation(value = "会员查询销售顾问申请信息(state[0失败，1成功，2审核中，3未提交审核])")
    @RequestMapping(value = "/applyState/{userID}", method = RequestMethod.GET)
    public Object selectApplyState(@PathVariable Long userID) throws Exception {
        return userInfoService.selectApplyState(userID);
    }

    @ApiOperation(value = "按条件查询申请销售顾问列表")
    @RequestMapping(value = "/apply/{pageNum}/{pageSize}", method = RequestMethod.POST)
    public Object uaList(@PathVariable int pageNum, @PathVariable int pageSize, @RequestBody ApplyDto applyDto) throws Exception {
        return userInfoService.uaList(pageNum, pageSize, applyDto);
    }

    @ApiOperation(value = "添加用户意见[只需传userID和content]")
    @RequestMapping(value = "/feedback", method = RequestMethod.POST)
    public Object addFeedback(@RequestBody Feedback feedback) {
        return userInfoService.addFeedback(feedback);
    }

    @ApiOperation(value = "获取用户下订单需要得到的用户及其组织信息")
    @RequestMapping(value = "/userInfoForOrder/{userID}", method = RequestMethod.GET)
    public Object getUserInfoForOrder(@PathVariable Long userID) {
        return userInfoService.getUserInfoForOrder(userID);
    }

    @ApiOperation(value = "根据userIDList查询对应的手机号")
    @RequestMapping(value = "/userIDList", method = RequestMethod.POST)
    public Object selectMobileByUserIDList(@RequestBody List<Long> userIDList) {
        return userInfoService.selectMobileByUserIDList(userIDList);
    }

    @ApiOperation(value = "根据userID查询对应的系统管理员及其用户类型")
    @RequestMapping(value = "/adminID/{oID}", method = RequestMethod.GET)
    public Object selectAdminIDByUserID(@PathVariable Long oID) {
        return userInfoService.selectAdminIDByUserID(oID);
    }


    @ApiOperation(value = "用户新增银行卡")
    @RequestMapping(value = "/userBankCard", method = RequestMethod.POST)
    public Object addUserBankCard(@RequestBody BankCard bankCard) {
        return userInfoService.addUserBankCard(bankCard);
    }

    @ApiOperation(value = "用户修改银行卡信息")
    @RequestMapping(value = "/userBankCard/update", method = RequestMethod.POST)
    public Object updateUserBankCard(@RequestBody BankCard bankCard) {
        return userInfoService.updateUserBankCard(bankCard);
    }

    @ApiOperation(value = "删除银行卡信息")
    @RequestMapping(value = "/userBankCard/delete/{id}", method = RequestMethod.GET)
    public Object deleteUserBankCards(@PathVariable Long id) {
        return userInfoService.deleteUserBankCard(id);
    }

    @ApiOperation(value = "按id查询银行卡信息")
    @RequestMapping(value = "/userBankCard/{id}", method = RequestMethod.GET)
    public Object selectUserBankCardByID(@PathVariable Long id) {
        return userInfoService.selectUserBankCardByID(id);
    }

    @ApiOperation(value = "按userID查询银行卡列表")
    @RequestMapping(value = "/userBankCardList/{userID}", method = RequestMethod.GET)
    public Object selectUserBankCardByUserID(@PathVariable Long userID) {
        return userInfoService.selectUserBankCardsByUserID(userID);
    }

    @ApiOperation(value = "按userID查询默认银行卡信息")
    @RequestMapping(value = "/userDefaultBankCard/{userID}", method = RequestMethod.GET)
    public Object selectUserBankCardDefaultByUserID(@PathVariable Long userID) {
        return userInfoService.selectUserDefaultBankCardByUserID(userID);
    }

    @ApiOperation(value = "设置默认用户银行卡信息")
    @RequestMapping(value = "/updateUserDefaultBankCard/{cardID}", method = RequestMethod.GET)
    public Object updateUserDefaultBankCard(@PathVariable Long cardID) {
        return userInfoService.updateUserBankCardDefault(cardID);
    }


    //create by zll 2017/4/11
    @ApiOperation(value = "批量查询用户的各个架构信息以及部分个人信息")
    @RequestMapping(value = "/userInfoMain", method = RequestMethod.POST)
    public Object getUserInfo(@RequestBody List<Long> idList) {
        return userInfoService.getUserInfoDetails(idList);
    }


    @ApiOperation(value = "根据address的List得到对应的信息Map")
    @RequestMapping(value = "/addressInfoMap", method = RequestMethod.POST)
    public Object getAddressMapByIds() {
        return userInfoService.getAddressMap();
    }


    @ApiOperation(value = "得到总部信息")
    @RequestMapping(value = "/getLevel1Id", method = RequestMethod.GET)
    public Object getLevel1() {
        return organizationalService.getLevel1(SystemContext.getCompanyID());
    }

    @ApiOperation(value = "得到抛转组织架构以及人员信息")
    @RequestMapping(value = "/getMaintenance", method = RequestMethod.GET)
    public Object getMaintenanceData() {
        return userInfoService.getMaintenanceData();
    }

    @ApiOperation(value = "根据PID查询推荐码")
    @RequestMapping(value = "getRecommendNoByPaterID/{paterID}", method = RequestMethod.GET)
    public Object getRecommendNoByPaterID(@PathVariable Long paterID) {
        UserInfo userInfo = userInfoService.getRecommendNoByPaterID(paterID);
        return userInfo == null ? "" : userInfo.getRecommendNO();
    }

    @ApiOperation(value = "根据名字查询某个组织下面的理财经理")
    @RequestMapping(value = "/selectByLikeName/{organizationalId}/{searchName}", method = RequestMethod.GET)
    public Object getSaleManagerListByOrg(@PathVariable Long organizationalId, @PathVariable String searchName) throws Exception {
        return userInfoService.getSaleManagerIDByName(organizationalId, searchName);
    }

    @ApiOperation(value = "查询会员&员工统计数据")
    @RequestMapping(value = "/selectEmpMembCountData/{level}/{organizationalId}", method = RequestMethod.GET)
    public Object selectEmpMembCountData(@PathVariable Integer level,
                                         @PathVariable Long organizationalId) throws Exception {
        Map<String, Object> map = Maps.newHashMap();
        Long twoLevelBranchNum = userInfoService.countTwoLevelBranchNum(organizationalId);
        map.put("twoLevelBranchNum", twoLevelBranchNum);
        Long subbranchNum = userInfoService.countSubbranchNum(level, organizationalId);
        map.put("subbranchNum", subbranchNum);
        Count count = (Count) countService.selectUserStatCount(0l, organizationalId);
        map.put("employeeRegNum", count.getSalesManagerID());
        map.put("membereRegNum", count.getMemberCount());
        if (level > 0) {
            Long employeeActNum = userInfoService.countEmployeeActNum(level, organizationalId);
            map.put("employeeActNum", employeeActNum);
        }
        return map;
    }

    @ApiOperation(value = "查询员工激活数")
    @RequestMapping(value = "/selectEmployeeActNum/{level}/{organizationalId}", method = RequestMethod.GET)
    public Object selectEmployeeActNum(@PathVariable Integer level,
                                       @PathVariable Long organizationalId) throws Exception {
        return userInfoService.countEmployeeActNum(level, organizationalId);
    }

    @ApiOperation(value = "分部员工数")
    @RequestMapping(value = "/branchEmployee/{level}/{branchID}", method = RequestMethod.GET)
    public Object branchEmployee(@PathVariable Integer level, @PathVariable Long branchID) throws Exception {
        List<UserOrganizationalInfoVo> list = userInfoService.branchEmployee(level, level + 1, branchID, SystemContext.getCompanyID());
        for (UserOrganizationalInfoVo uVo : list) {
            uVo.setTotalEmpNum(uVo.getEmployeeNum() + uVo.getTwoBranchEmpNum() + uVo.getSubbranchEmpNum());
        }
        return list;
    }

    @ApiOperation(value = "分部会员数")
    @RequestMapping(value = "/branchMember/{level}/{branchID}", method = RequestMethod.GET)
    public Object branchMember(@PathVariable Integer level, @PathVariable Long branchID) throws Exception {
        List<UserOrganizationalInfoVo> list = userInfoService.branchMember(level, level + 1, branchID);
        for (UserOrganizationalInfoVo uVo : list) {
            uVo.setTotalMemNum(uVo.getMemberNum() + uVo.getTwoBranchMemNum() + uVo.getSubbranchMemNum());
        }
        return list;
    }

    @ApiOperation(value = "理财经理的会员注册数")
    @RequestMapping(value = "/memberNumBySalesManager/{salesManagerID}", method = RequestMethod.GET)
    public Object memberNumBySalesManager(@PathVariable Long salesManagerID) throws Exception {
        return userInfoService.countMemberBySalesManager(salesManagerID);
    }

    @ApiOperation(value = "根据ID查询用户(附加是否是管理员的身份)")
    @RequestMapping(value = "/dept/{userID}", method = RequestMethod.GET)
    public Object userWithDept(@PathVariable Long userID) {
        return userInfoService.selectWithDeptByUserID(userID);
    }

    //更新syscount
    @ApiOperation(value = "根据ID查询用户(附加是否是管理员的身份)")
    @RequestMapping(value = "/sys", method = RequestMethod.GET)
    public Object sys() {
        return userInfoService.sys();
    }

    @ApiOperation(value = "定时任务审核三天未审核的部门调度")
    @RequestMapping(value = "/handleExpiredTransfer", method = RequestMethod.GET)
    public Object handleExpiredTransfer() {
        return userInfoService.handleExpiredTransfer();
    }

    @ApiOperation(value = "查询所有用户")
    @RequestMapping(value = "/selAllUser/{companyID}", method = RequestMethod.GET)
    public Object selAllUser(@PathVariable Long companyID) {
        return userInfoService.selAllUser(companyID);
    }


    @ApiOperation(value = "创建一个token")
    @RequestMapping(value = "/token/{userID}", method = RequestMethod.GET)
    public Object createTk(@PathVariable Long userID) {
        return userInfoService.createToken(userID);
    }

    @ApiOperation(value = "获取token")
    @RequestMapping(value = "/gtoken/{userID}", method = RequestMethod.GET)
    public Object getTk(@PathVariable Long userID) {
        return userInfoService.getTokenFromRedis(userID);
    }


    //以上代码生成随机秘钥
    @ApiOperation(value = "创建一个随机token")
    @RequestMapping(value = "/seckey/create", method = RequestMethod.GET)
    public Object createRandomTk(HttpServletRequest request) {
        return userInfoService.createToken(request);
    }

    @ApiOperation(value = "获取token")
    @RequestMapping(value = "/seckey/{key}", method = RequestMethod.GET)
    public Object getRandomTk(@PathVariable String key) {
        return userInfoService.getTokenFromRedis(key);
    }

    @ApiOperation(value = "获取用户权限")
    @RequestMapping(value = "/userPermission/{userID}", method = RequestMethod.GET)
    public Object userPermission(@PathVariable Long userID) {
        List<String> funCodeList = new ArrayList();
        UserInfo userInfo = userInfoService.selectByUserID(userID);
        funCodeList = userInfoService.getFunCodeByUserID(userInfo.getUserID());
        return funCodeList;
    }

    @ApiOperation(value = "批量修改会员推荐人")
    @RequestMapping(value = "/recommenders", method = RequestMethod.POST)
    public Object batchUpdateRecommender(@RequestBody RecommenderDto dto) throws Exception {
        return userInfoService.batchUpdateRecommender(dto);
    }

    /**
     * 维护会员和采购商的部门
     *
     * @param userType
     * @return
     */
    @RequestMapping(value = "/initData/{userType}", method = RequestMethod.GET)
    public Object initData(@PathVariable Integer userType) {
        return userInfoService.initData(userType);
    }

    @ApiOperation(value = "初始化会员信息到erp")
    @RequestMapping(value = "/maintenceDataMember", method = RequestMethod.GET)
    public Object mainMemberInfo() {
        int i = (int) userInfoService.initDataMember();
        return i;
    }


    /**
     * 获取用户等级
     *
     * @param userID
     * @return
     */
    @RequestMapping(value = "/getUserGradeByUserID/{userID}", method = RequestMethod.GET)
    public Object getUserGradeByUserID(@PathVariable Long userID) {
        return userInfoService.getUserGradeByUserID(userID);
    }

    /**
     * 获取店长ID根据userID
     *
     * @param userID
     * @return
     */
    @RequestMapping(value = "/getStoreManagerByUserID/{userID}", method = RequestMethod.GET)
    public Object getStoreManagerByUserID(@PathVariable Long userID) {
        return userInfoService.getStoreManagerByUserID(userID);
    }


}
